package com.example.gaojt.androiddemo.statical.sdk;

import android.content.ContentValues;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.Process;
import android.util.Log;

import java.util.Map;


/**
 * Created by gaojt on 7/9/17.
 */

final class StatisticsManager {
    private static final String TAG = "StatisticsManager";
    private static Context mContext;
    private static Handler mDBHandler;
    private static String mProcessName;
    private SendService mSendService;
    private boolean mDebug;
    private StatisticsApi.Config mConfig;

    public StatisticsManager(Context context, String processName, StatisticsApi.Config config, boolean debug) {
        mContext = context;
        String packageName = context.getPackageName();
        if (packageName.equals(processName)) {
            mProcessName = "main";
        } else {
            int processNameLength = processName.length();
            int packageNameLength = packageName.length();
            mProcessName = processName.substring(packageNameLength + 1, processNameLength - 1);
        }
        if (debug) {
            Log.d(TAG, "StatisticsManager: mProcessName = " + mProcessName);
        }
        mConfig = config;
        mDebug = debug;
        mSendService = new SendService(context, mProcessName);
        initWorker();
    }

    private void initWorker() {
        HandlerThread handlerThread = new HandlerThread("log db worker", Process.THREAD_PRIORITY_BACKGROUND);
        handlerThread.start();
        mDBHandler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                EventItem event = (EventItem) msg.obj;
                event.setCommonParams(CommonParams.getCommonParams(mContext, mConfig));
                String content = StatisticsUtils.convertEventItem2Json(event, mConfig);
                if (mDebug) {
                    Log.d(TAG, "handleMessage: content = " + content);
                }
                reportLog(content);
            }
        };
    }

    void onEvent(final String eventName, final Map<String, String> map) {
        EventItem event = new EventItem(System.currentTimeMillis(), eventName, map);
        Message message = mDBHandler.obtainMessage();
        message.obj = event;
        message.sendToTarget();
    }

    /**
     * report log
     *
     * @param log
     */
    private void reportLog(String log) {

        // 存入数据库，触发网络线程去读取数据执行上传
        synchronized (LogInfoDB.LOCK) {
            LogInfoDB db = new LogInfoDB(mContext, mProcessName);
            try {
                ContentValues values = new ContentValues();
                values.put(LogInfoDB.COLUMN_MSG, log);
                db.insert(values);
            } catch (Exception e) {
                Log.w(TAG, "reportLog: ", e);
            } finally {
                db.close();
            }
        }
        mSendService.send();

    }

    void onEvent(final String eventName) {
        EventItem event = new EventItem(System.currentTimeMillis(), eventName);
        Message message = mDBHandler.obtainMessage();
        message.obj = event;
        message.sendToTarget();
    }
}
